package com.hxgis.oc.product.base;

import cn.hutool.core.collection.ConcurrentHashSet;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ProductFactoryWorker {
    private ThreadPoolExecutor threadPoolExecutor;
    private ConcurrentHashSet<String> workingSet = new ConcurrentHashSet<>();

    public ProductFactoryWorker(){
        init(1);
    }

    public ProductFactoryWorker(int threadNum){
        init(threadNum);
    }

    private void init(int threadNum){
        threadPoolExecutor = new ThreadPoolExecutor(1, threadNum, 30,
                TimeUnit.SECONDS,
                new PriorityBlockingQueue<>(11),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());
    }

    public void addTask(ProduceTask produceTask)
    {
        String key = produceTask.getDataSet() + produceTask.getFileID();
        if(workingSet.contains(key))
        {
            return;
        }
        workingSet.add(key);
        threadPoolExecutor.execute(produceTask);
    }
}
